﻿using System;
using System.ComponentModel.DataAnnotations;
using System.Text.RegularExpressions;
using DataAnnotationsExtensions.Resources;

namespace DataAnnotationsExtensions
{
    [AttributeUsage(AttributeTargets.Property, AllowMultiple = false)]
    public class StringArrayMaxLengthAttribute : DataTypeAttribute
    {
        private int _errorType; 
        public int MaximumCount { get; set; }
        public int MaximumLengthForInnerEach { get; set; }
        public string Delimeter { get; set; }
        public string ErrorMessageForInnerEach { get; set; }

        public StringArrayMaxLengthAttribute()
            : base(DataType.Text)
        {
        }

        public override string FormatErrorMessage(string name)
        {
            if (_errorType == 1)
            {
                if (ErrorMessage == null)
                {
                    ErrorMessage = ValidatorResources.StringArrayMaxLengthAttribute_CountInvalid;
                }

                return string.Format(ErrorMessage, name, MaximumCount);
            }
            else
            {
                if (ErrorMessageForInnerEach == null)
                {
                    ErrorMessageForInnerEach = ValidatorResources.StringArrayMaxLengthAttribute_LengthForEachInvalid;
                }

                return string.Format(ErrorMessageForInnerEach, name, MaximumLengthForInnerEach);
            }
        }

        public override bool IsValid(object value)
        {
            if (value == null)
            {
                return true;
            }

            string valueAsString = value as string;
            string[] result = valueAsString.Split(new string[] { Delimeter }, StringSplitOptions.RemoveEmptyEntries);
            if (result.Length > MaximumCount)
            {
                _errorType = 1;
                return false;
            }
            else
            {
                foreach (var str in result)
                {
                    if (str.Length > MaximumLengthForInnerEach)
                    {
                        _errorType = 2;
                        return false;
                    }
                }
            }
            return true;
        }

        
    }
}
